<template>
  <view
    :class="[
      ns.b(),
      disabled ? ns.m('disabled') : '',
      readonly ? ns.m('readonly') : '',
    ]"
  >
    <text v-if="readonly">{{ getReadonly() }}</text>
    <i-biz-input-base
      v-else
      ref="inputRef"
      type='number'
      v-model="currentVal"
      :placeholder="controller.placeHolder"
      :precision="c.model.precision"
      :disabled="disabled"
      @focus="onFocus"
      @blur="onBlur"
      @input="handleChange"
    >
    </i-biz-input-base>
    <i v-if="c.parent.unitName" :class="ns.e('unit')">{{ c.parent.unitName }}</i>
  </view>
</template>
<script lang="ts">
export default {
  options: {
    addGlobalClass: true,
    virtualHost: true,
    styleIsolation: "shared"
  }
}
</script>
<script setup lang="ts">
import { ref, watch } from "vue";
import { floor } from "lodash-es";
import { getEditorEmits, getInputNumberProps } from "@/props";
import { useNamespace } from "@/use";
import { TextBoxEditorController } from "../i-biz-text-box-editor.controller";


const props = defineProps(getInputNumberProps<TextBoxEditorController>());
const emit = defineEmits(getEditorEmits());

const ns = useNamespace("input-number");

const c = props.controller;

const currentVal = ref<number | undefined>(undefined);

const oldEmitVal = ref<number | undefined>(undefined);

watch(
  () => props.value,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      const number = Number(newVal);
      currentVal.value = Number.isNaN(number) ? undefined : number;
    }
  },
  { immediate: true }
);

const handleChange = (evt: IData) => {
  const value = Number(evt.value);

  const emitValue = evt.value ? floor(value, c.precision) : undefined;
  if (emitValue === oldEmitVal.value) {
    return;
  }
  emit("change", emitValue);
  oldEmitVal.value = Number(emitValue);
};

const inputRef = ref();

if (props.autoFocus) {
  watch(inputRef, (newVal) => {
    if (newVal) {
      const input = newVal.$el.getElementsByTagName("input")[0];
      input.focus();
    }
  });
}

// 聚焦
const onFocus = () => {
  emit("focus");
};

// 失焦
const onBlur = () => {
  emit("blur");
};

const getReadonly = () => {
  // 只读显示
  let content = `${currentVal.value || ''}`;
  const { unitName } = c.parent;
  // 当有值且单位存在时才显示单位
  if (content && unitName) {
    content += unitName;
  }
  return content;
}
</script>
<style lang="scss">
@import "./i-biz-input-number.scss";
</style>